package top.mcwebsite.playandroid.common.uiWidget

import android.util.Log
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import kotlin.math.roundToInt
import top.mcwebsite.lib.skeleton.SkeletonDefault
import top.mcwebsite.lib.skeleton.SkeletonHighlight
import top.mcwebsite.lib.skeleton.shimmer
import top.mcwebsite.lib.skeleton.skeleton

@Composable
public fun SkeletonDefault.color(
    backgroundColor: Color = MaterialTheme.colorScheme.surface,
    contentColor: Color = contentColorFor(backgroundColor),
    contentAlpha: Float = 0.1f,
): Color = contentColor.copy(contentAlpha).compositeOver(backgroundColor)


@Composable
fun SkeletonDefault.shimmerHighlightColor(
    backgroundColor: Color = MaterialTheme.colorScheme.inverseSurface,
    alpha: Float = 0.75f,
): Color {
    return backgroundColor.copy(alpha = alpha)
}

fun Modifier.skeleton(visible: Boolean) = composed {
    skeleton(
        visible = visible,
        shape = MaterialTheme.shapes.small,
        color = SkeletonDefault.color(),
        highlight = SkeletonHighlight.shimmer(
            highlightColor = SkeletonDefault.shimmerHighlightColor(),
        ),
    )
}

@Composable
fun SkeletonPage(
    content: @Composable () -> Unit
) {
    BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
        val height = with(LocalDensity.current) { maxHeight.toPx() }
        Log.d("mengchen", "maxWidth = $height")
        val rememberCount = remember {
            mutableIntStateOf(1)
        }
        val isInit = remember {
            mutableStateOf(false)
        }
        Column {
            repeat(rememberCount.intValue) {
                Box(
                    modifier = Modifier.onGloballyPositioned {
                        if (!isInit.value) {
                            rememberCount.intValue = (height / it.size.height).roundToInt()
                            isInit.value = true
                        }
                    }
                ) {
                    content()
                }
            }
        }
    }
}